package process_demo.review.blocking_queue;

/**
 * @author haomin
 * @date 2022/09/12 12:24
 **/
public class MyArrayBlockingQueue {
    private long[] array;
    private int frontIndex;
    private int rearIndex;
    private int size;

    public MyArrayBlockingQueue (int capacity){
        array = new long[capacity];
        frontIndex = 0;
        rearIndex = 0;
        size = 0;
    }

    public synchronized void put (long val) throws InterruptedException {
        // while 防止假唤醒
        while(size == array.length){
            this.wait();
        }

        // 预期：队列一定不是满的
        array[rearIndex] = val;
        rearIndex++;
        if(rearIndex == array.length){
            rearIndex = 0;
        }

        // notify();
        // 在多生产者，多消费者时用notifyAll()
        notifyAll();
    }

    public synchronized long take () throws InterruptedException {
        while(size == 0){
            wait();
        }

        long val = array[frontIndex];
        frontIndex++;
        if(frontIndex == array.length){
            frontIndex = 0;
        }

        // notify();
        // 在多生产者，多消费者时用notifyAll()
        notifyAll();
        return val;
    }
}